package informationExtractionSystem;

import java.util.ArrayList;

import workload.impl.condition.UsefulCondition;


import com.clearforest.OpenCalaisRelationExtractor;

import database.mediator.MediatorInterface;
import distributedRE.model.Document;
import distributedRE.model.Relation;
import distributedRE.model.Tuple;

public class OpenCalaisExtractor extends InformationExtractor {

	private OpenCalaisRelationExtractor oCRE;

	private Relation relation;

	private String newName;

	private UsefulCondition usefulCondition;
	
	
	public OpenCalaisExtractor(String Id, MediatorInterface mI, Relation relation, UsefulCondition usefulCondition, String newName, String table) {
		super(Id, mI);
		oCRE = new OpenCalaisRelationExtractor("/home/pjbarrio/workspace/opencalais/calaisParams.xml",table);
		this.relation = relation;
		this.newName = newName;
		this.usefulCondition = usefulCondition;

	}

	@Override
	protected ArrayList<Tuple> extractTuples(Document document) {
		
		String result = oCRE.IEProcess(document.getPath(), newName);
			
		ArrayList<ArrayList<String>> tuples = oCRE.extractTuples(relation.getName(),result);
			
		ArrayList<Tuple> res = new ArrayList<Tuple>();
		
		for (ArrayList<String> arrayList : tuples) {
			
			String text = "";
			
			for (String string : arrayList) {
				
				text = text + string + ";";
				
			}
			
			text = text.substring(0,text.length()-1); //Remove the last ";"
			
			Tuple t = new Tuple(new Long(getId()).longValue(),relation.getId(), mI.getNextTupleId(new Long(getId()).longValue(),relation.getId()), text, Tuple.NO_ROOT_DETECTED, Tuple.NO_ROOT_DETECTED, Tuple.NO_ROOT_DETECTED);
			
			res.add(t);
			
		}
		
		return res;
		
	}

	public int isUseful(Relation r,Document document) {
		
		ArrayList<Tuple> t = getStoredTuples(r,document);
		
		qxtract.tuple.Tuple[] tuples = new qxtract.tuple.Tuple[t.size()]; 
		
		int i = 0;
		
		for (Tuple tuple : t) {
		
			tuples[i] = tuple.getProcessableTuple();
			
			i++;
		}
		
		if (usefulCondition.isItUseful(tuples))
			return USEFUL_VALUE;
		if (usefulCondition.isItUseless(tuples))
			return USELESS_VALUE;
		return NOT_DEFINED_VALUE;
	}

}
